<?php
	include "../../config/koneksi.php";
	$sukses = 0;
	$gagal = 0;
	echo $_POST['userfile'];
	if ($_FILES[userfile][size] > 0) {

		//get the csv file
		$file = $_FILES[userfile][tmp_name];
		$handle = fopen($file,"r");

		//loop through the csv file and insert into database
		do {
			$no++;
			if($no > 2){
				if ($data[0]) {
					$kode = addslashes($data[1]);
					$deskripsi = addslashes($data[2]);
					$alos = addslashes($data[3]);
					$id_jenis = addslashes($data[4]);
					$jenis = addslashes($data[5]);
					$klaim = addslashes($data[6]);
					$jml = mysql_num_rows(mysql_query("select kode_inacbg from master_inacbg where kode_inacbg = '$kode'"));
					if($jml > 0){
						$query = "update master_inacbg set deskripsi = '$deskripsi', alos=$alos, id_jenis_inacbg = $id_jenis, not_klaim = '$klaim' where kode_inacbg = '$kode'";
					}else{
						$query = "insert into master_inacbg values ('$kode','$deskripsi',$alos,$id_jenis,'$klaim')";
					}
					
					$hasil = mysql_query($query);
					if ($hasil){
						$sukses++;
					}
					else{
						$gagal++;
						$data_gagal[$gagal] = array(
							"kode" => "$kode",
							"deskripsi" => "$deskripsi",
							"alos" => "$alos",
							"id_jenis" => "$id_jenis",
							"jenis" => "$jenis",
							"klaim" => "$klaim"
						);
					}
				}
			}
		} while ($data = fgetcsv($handle,3000,";","'"));
	}
	
	if($gagal > 0){
		$content = "Sukses;$sukses\nGagal;$gagal\n\nNO;KODE;DESKRIPSI;ALOS;KODE JENIS;JENIS;NOT KLAIM\n";
		for($i=1;$i<=$gagal;$i++){
			$content .= "$i;".$data_gagal[$i]['kode'].";".$data_gagal[$i]['deskripsi'].";".$data_gagal[$i]['alos'].";".$data_gagal[$i]['id_jenis'].";".$data_gagal[$i]['jenis'].";".$data_gagal[$i]['klaim']."\n";
		};

		header("Content-type: text/csv");
		header("Content-Disposition: attachment; filename=Gagal_Import_INACBG.csv");
		header("Pragma: no-cache");
		header("Expires: 0");
		echo $content;
	}else{
		echo "<h3>Proses import data selesai.</h3>";
		echo "<p>Jumlah data yang sukses diimport : ".$sukses."<br>";
		echo "Jumlah data yang gagal diimport : ".$gagal."</p>";
	}
?>